﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using WebMatrix.WebData;
using WebMatrix.Data;
using OpenWeb.Dal.Models;
using System.Web.Security;


namespace OpenWeb.Dal.DbCreation
{
  public abstract class PopolaDb
  {

    public PopolaDb()
    {
    }

    public void PopolaIlDatabaseConDati(DbContext pContext)
    {

      var contesto = pContext as ApplicationDbEntities;
      if (contesto == null) 
        throw new ArgumentException("Errore : In PopolaDb contesto non valido !");

      if(!WebSecurity.Initialized )
        WebSecurity.InitializeDatabaseConnection (GlobalInfo.ConnStringName, "UserProfile", "UserId", "UserName",autoCreateTables: true);

      WebSecurity.CreateUserAndAccount("testadmin", "test00");

      var roles = (SimpleRoleProvider)Roles.Provider; //(SimpleRoleProvider)
      var membership = (SimpleMembershipProvider)Membership.Provider;

        //crea ruoli
      if (!roles.RoleExists("AdminRole"))roles.CreateRole("AdminRole");
      if (!roles.RoleExists("UserRole")) roles.CreateRole("UserRole");
      
      if (membership.GetUser("testuser1", false) == null)
        membership.CreateUserAndAccount("testuser1", "test11");
      
        // setta Ruoli
      if (!roles.GetRolesForUser("testadmin").Contains("AdminRole"))
        roles.AddUsersToRoles(new[] { "testadmin" }, new[] { "UserRole" });

      if (!roles.GetRolesForUser("testuser1").Contains("UserRole"))
          roles.AddUsersToRoles(new[] { "testuser1" }, new[] { "UserRole" });

      pContext.SaveChanges(); // OK 1 ?

      List<Contact> lista = new List<Contact>()
      {
        new Contact(){ Name ="testuser1", Surname="test", IsPerson=true,
          ContactType= 1 , Guid= Guid.NewGuid()  ,
          Adresses = new List<Address>() { new Address() { Location= "Mi", Adress="via gnocchi", City= "Co", State= "Italy"} } ,
           Reminders = new List<Reminder>(){  new Reminder(){ Date = DateTime.Now  }}
          ,Profile = new ContactProfile(){  Evaluation= 1 }          
        
        }     ,

        new Contact(){ Name ="testuser2", Surname="test", IsPerson=false,
          ContactType= 2 , Guid= Guid.NewGuid() },

      };

      lista.ForEach(xx => contesto.Contacts.Add(xx));
      
      pContext.SaveChanges();

    }




  }
}
